package cn.otrue.patienthealthmanager.activity;

import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.adapter.MyFragmentPagerAdpater;
import cn.otrue.patienthealthmanager.bean.HistoryChat;
import cn.otrue.patienthealthmanager.db.DBTools;
import cn.otrue.patienthealthmanager.fragment.FindDoctorFragment;
import cn.otrue.patienthealthmanager.fragment.HealthyComyFragment;
import cn.otrue.patienthealthmanager.fragment.MainFragment;
import cn.otrue.patienthealthmanager.fragment.PersonalCenterFragment;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.MyViewPager;
import cn.otrue.patienthealthmanager.xmpp.XmppTool;

import com.jauker.widget.BadgeView;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.umeng.update.UmengUpdateAgent;

/**
 * 主页面 主容器
 * 
 * @author G
 * 
 */
public class MainActivity extends BaseActivity {
	public static int pushNum = 0;
	protected static final int GET_WAIT_FOR_AUTHOR_LIST = 1120;
	/** 上传本地应用列表 */

	private MyViewPager viewPager;
	private TextView firstBtn;
	private TextView secondBtn;
	private TextView thirdBtn;
	private TextView fourthBtn;
	/** 当前被激活的按钮 */
	private TextView currentFoucsedBtn;

	public String currentCity;
	/* 关注人的userId* */
	public String userIdOfAttener = null;
	private View moveView;
	private View firstView;
	private View secondView;
	private View thirdView;
	private View fourthView;
	private View targetView;
	private int left = 0;
	private MyFragmentPagerAdpater viewpagerAdapter;
	private BadgeView badgeView;
	private BadgeView badgeViewPush;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		CommonUtil.getHig(this);
		MyConst.activity = this;
		//UmengUpdateAgent.update(this);
		int currentItem = getCurrentItem();
		// startPush();
		initView(currentItem);

	}

	Handler numHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			badgeView.setBadgeCount(num);
		}

	};

	public void getPush() {

		pushHandler.sendMessage(new Message());
	}

	private Handler pushHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			badgeViewPush.setBadgeCount(pushNum);
		}

	};

	private int num;

	public void initNum() {

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					List<HistoryChat> list = DBTools.db.findAll(Selector.from(
							HistoryChat.class).where("patientUser", "=",
							MyConst.getACCOUNT()));
					num = 0;
					if (list != null && list.size() > 0) {
						for (int i = 0; i < list.size(); i++) {
							num = num + list.get(i).getUnreadNum();
						}

					}
					numHandler.sendMessage(new Message());

				} catch (DbException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}

	private int getCurrentItem() {
		Intent intent = getIntent();
		return intent.getIntExtra("currentItem", 0);
	}

	private void initView(int currentItem) {

		TextView tvt = (TextView) findViewById(R.id.tv_title_title);

		tvt.setText(getString(R.string.app_name));

		// 先初始化ViewPager
		initViewPager(currentItem);

		firstBtn = (TextView) findViewById(R.id.ico_catt_first);
		firstBtn.setOnClickListener(this);

		secondBtn = (TextView) findViewById(R.id.ico_catt_second);
		secondBtn.setOnClickListener(this);

		thirdBtn = (TextView) findViewById(R.id.ico_catt_third);
		thirdBtn.setOnClickListener(this);

		fourthBtn = (TextView) findViewById(R.id.ico_catt_fourth);
		fourthBtn.setOnClickListener(this);

		badgeView = new BadgeView(this);
		badgeView.setTargetView(secondBtn);
		badgeViewPush = new BadgeView(this);
		badgeViewPush.setTargetView(fourthBtn);

		// 为每个按钮设置一个Tag 动态变化时，即可自行设置相应的背景
		int[] Btn_bgs = { R.drawable.ico_common_tools_foucsed,
				R.drawable.ico_common_tools_normal, 0 };
		firstBtn.setTag(Btn_bgs);
		int[] Btn_bgs2 = { R.drawable.ico_data_pick_foucsed,
				R.drawable.ico_data_pick_normal, 1 };
		secondBtn.setTag(Btn_bgs2);
		int[] Btn_bgs3 = { R.drawable.ico_data_view_focused,
				R.drawable.ico_data_view_normal_parent, 2 };
		thirdBtn.setTag(Btn_bgs3);
		int[] Btn_bgs4 = { R.drawable.ico_usercenter_foucsed,
				R.drawable.ico_usercenter_normal_parent, 3 };
		fourthBtn.setTag(Btn_bgs4);

		moveView = findViewById(R.id.iv_catt_move);
		if (left != 0) {
			LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.MATCH_PARENT);
			ll.setMargins(left, 0, 0, 0);
			moveView.setLayoutParams(ll);
		}
		firstView = findViewById(R.id.iv_catt_img1);
		targetView = firstView;
		secondView = findViewById(R.id.iv_catt_img2);
		thirdView = findViewById(R.id.iv_catt_img3);
		fourthView = findViewById(R.id.iv_catt_img4);
		int textsize = 13;
		float currentScale = CommonUtil
				.getCurrentScale(getApplicationContext());

		if (currentScale <= 1.5) {
			textsize = 13;

		}

		initParentTabBtn(firstBtn, getString(R.string.main), textsize);
		initParentTabBtn(secondBtn, getString(R.string.find_doctor), textsize);
		initParentTabBtn(thirdBtn, getString(R.string.healthy_community),
				textsize);
		initParentTabBtn(fourthBtn, getString(R.string.personal_center),
				textsize);
		switch (currentItem) {
		case 0:
			currentFoucsedBtn = firstBtn;
			changeBtnState(true, currentFoucsedBtn);
			changeBtnState(false, secondBtn);
			changeBtnState(false, thirdBtn);
			changeBtnState(false, fourthBtn);
			break;
		case 1:
			currentFoucsedBtn = secondBtn;
			changeBtnState(true, currentFoucsedBtn);
			changeBtnState(false, firstBtn);
			changeBtnState(false, thirdBtn);
			changeBtnState(false, fourthBtn);
			break;
		case 2:
			currentFoucsedBtn = thirdBtn;
			changeBtnState(true, currentFoucsedBtn);
			changeBtnState(false, firstBtn);
			changeBtnState(false, secondBtn);
			changeBtnState(false, fourthBtn);
			break;
		case 3:
			currentFoucsedBtn = fourthBtn;
			changeBtnState(true, currentFoucsedBtn);
			changeBtnState(false, firstBtn);
			changeBtnState(false, secondBtn);
			changeBtnState(false, thirdBtn);
			break;
		}
	}

	/**
	 * 初始化Fragment的容器---ViewPager
	 * 
	 * @param currentItem
	 */
	private void initViewPager(int currentItem) {

		viewPager = (MyViewPager) findViewById(R.id.vp_main_viewPager);
		viewpagerAdapter = new MyFragmentPagerAdpater(
				getSupportFragmentManager());
		viewpagerAdapter.addFragment(MainFragment.newInstance());
		viewpagerAdapter.addFragment(FindDoctorFragment.newInstance());
		viewpagerAdapter.addFragment(HealthyComyFragment.newInstance());
		viewpagerAdapter.addFragment(PersonalCenterFragment.newInstance());

		viewPager.setAdapter(viewpagerAdapter);
		viewPager.setOffscreenPageLimit(3);

		// viewPager.setOnTouchListener(new OnTouchListener() {
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// return true;
		// }
		// });
		viewPager.setCurrentItem(currentItem);
	}

	public MyViewPager getViewPager() {
		return viewPager;
	}

	private void initParentTabBtn(TextView textBtn, String btnTitle,
			int textsize) {
		findViewById(R.id.fl_catt_third).setVisibility(View.VISIBLE);
		findViewById(R.id.v_catt_topLine).setBackgroundColor(
				getResources().getColor(R.color.blue_text));

		LayoutParams params = textBtn.getLayoutParams();
		params.height = LayoutParams.MATCH_PARENT;
		params.width = LayoutParams.MATCH_PARENT;
		textBtn.setLayoutParams(params);

		textBtn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textsize);
		textBtn.setText(btnTitle);
	}

	@Override
	public void onClick(View v) {
		if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
			initNum();
		}

		switch (v.getId()) {
		case R.id.ico_catt_first:

			MainFragment.gotoFragment(4);
			if (firstBtn != currentFoucsedBtn) {
				// if (version_id == MyConst.VERSION_CHILDREN)

				viewPager = (MyViewPager) findViewById(R.id.vp_main_viewPager);
				viewpagerAdapter = new MyFragmentPagerAdpater(
						getSupportFragmentManager());
				viewpagerAdapter.addFragment(MainFragment.newInstance());
				viewpagerAdapter.addFragment(FindDoctorFragment.newInstance());
				viewpagerAdapter.addFragment(HealthyComyFragment.newInstance());
				viewpagerAdapter.addFragment(PersonalCenterFragment
						.newInstance());
				viewPager.setCurrentItem(0);
				changeBtnState(true, firstBtn);
				changeBtnState(false, currentFoucsedBtn);
				currentFoucsedBtn = firstBtn;
			} else {
				viewPager.setCurrentItem(0);
			}
			break;
		case R.id.ico_catt_second:

			if (secondBtn != currentFoucsedBtn) {

				viewPager.setCurrentItem(1);
				changeBtnState(false, currentFoucsedBtn);
				changeBtnState(true, secondBtn);
				currentFoucsedBtn = secondBtn;
				if (num > 0) {
					FindDoctorFragment.gotoFragment(3);
				}
			}
			break;
		case R.id.ico_catt_third:
			if (thirdBtn != currentFoucsedBtn) {
				viewPager.setCurrentItem(2);
				changeBtnState(false, currentFoucsedBtn);
				changeBtnState(true, thirdBtn);
				currentFoucsedBtn = thirdBtn;
			}
			break;
		case R.id.ico_catt_fourth:
			if (fourthBtn != currentFoucsedBtn) {
				viewPager.setCurrentItem(3);
				changeBtnState(false, currentFoucsedBtn);
				changeBtnState(true, fourthBtn);
				currentFoucsedBtn = fourthBtn;
			}
			break;

		}
	}

	private void moveTabBar(final TextView textBtn, View currentBtn) {
		View currentView = null;
		if (firstBtn.equals(currentFoucsedBtn)) {
			currentView = firstView;
		} else if (secondBtn.equals(currentFoucsedBtn)) {
			currentView = secondView;
		} else if (thirdBtn.equals(currentFoucsedBtn)) {
			currentView = thirdView;
		} else if (fourthBtn.equals(currentFoucsedBtn)) {
			currentView = fourthView;
		}
		if (firstBtn.equals(textBtn)) {
			targetView = firstView;
		} else if (secondBtn.equals(textBtn)) {
			targetView = secondView;
		} else if (thirdBtn.equals(textBtn)) {
			targetView = thirdView;
		} else if (fourthBtn.equals(textBtn)) {
			targetView = fourthView;
		}
		Animation animation = new TranslateAnimation(currentView.getLeft()
				- left, targetView.getLeft() - left, 0, 0);
		animation.setFillAfter(true);
		animation.setDuration(300);
		moveView.startAnimation(animation);
	}

	@Override
	protected void onResume() {
		MyConst.activity = this;
		if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {

		}
		super.onResume();

	}

	public static Drawable resizeImage(Bitmap bitmap, int w, int h) {
		Bitmap BitmapOrg = bitmap;
		int width = BitmapOrg.getWidth();
		int height = BitmapOrg.getHeight();
		int newWidth = w;
		int newHeight = h;

		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// if you want to rotate the Bitmap
		// matrix.postRotate(45);
		Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
				height, matrix, true);
		return new BitmapDrawable(resizedBitmap);
	}

	/**
	 * 更改主页上标签按钮的样式
	 * 
	 * @param b
	 *            是否为激活状态
	 * @param textBtn
	 */
	private void changeBtnState(boolean b, TextView textBtn) {
		if (b) {

			textBtn.setTextColor(getResources().getColor(R.color.main));
			int[] btn_bgs = (int[]) textBtn.getTag();

			Drawable drawable = resizeImage(
					BitmapFactory.decodeResource(getResources(), btn_bgs[0]),
					CommonUtil.dip2px(this, 48), CommonUtil.dip2px(this, 48));

			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());
			textBtn.setCompoundDrawables(null, drawable, null, null);
			if (!currentFoucsedBtn.equals(textBtn)) {
				moveTabBar(textBtn, currentFoucsedBtn);
			}
			return;
		} else {
			int[] btn_bgs = (int[]) textBtn.getTag();
			Drawable drawable = resizeImage(
					BitmapFactory.decodeResource(getResources(), btn_bgs[1]),
					CommonUtil.dip2px(this, 48), CommonUtil.dip2px(this, 48));
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());
			textBtn.setCompoundDrawables(null, drawable, null, null);
			textBtn.setTextColor(getResources().getColor(
					R.color.tab_bar_text_color));
			return;
		}
	}

	@Override
	protected void onDestroy() {
		XmppTool.closeConnection();
		MyConst.TOKEN = "";
		MyConst.setACCOUNT("");
		super.onDestroy();
	}

	public void gotoFragment(int i) {
		viewPager.setCurrentItem(i);
		switch (i) {
		case 1:
			if (secondBtn != currentFoucsedBtn) {
				viewPager.setCurrentItem(1);
				changeBtnState(false, currentFoucsedBtn);
				changeBtnState(true, secondBtn);
				currentFoucsedBtn = secondBtn;
			}
			break;
		case 2:
			if (thirdBtn != currentFoucsedBtn) {
				viewPager.setCurrentItem(2);
				changeBtnState(false, currentFoucsedBtn);
				changeBtnState(true, thirdBtn);
				currentFoucsedBtn = thirdBtn;
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
		}
		return true;
	}

	public void exit() {
		if (!isExit) {
			isExit = true;
			Toast.makeText(getApplicationContext(), "再按一次退出程序",
					Toast.LENGTH_SHORT).show();
			myhandler1.sendEmptyMessageDelayed(0, 5000);// 延迟5000毫秒后发送空消息
		} else {
			System.exit(0);
		}
	}

	private boolean isExit;
	private Handler myhandler1 = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			isExit = false;
		}
	};

}
